// toy sql lib

/**
宏开关
1. 用于color print, 我需要
COLOR_PRINT_IMPLEMENTATION

*/


#ifndef __MINISQL_H__
#define __MINISQL_H__

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>

// 开关
#define HAS_COLOR_PRINT
#ifdef HAS_COLOR_PRINT
#define COLOR_PRINT_IMPLEMENTATION
#include "color_print.h"
#endif

#ifdef _WIN32
#include <windows.h>
#define MINISQL_DIR_SEP "\\"
#else
#include <unistd.h>
#include <sys/stat.h>
#define MINISQL_DIR_SEP "/"
#endif

#ifdef __cplusplus
extern "C" {
#endif

// 状态码
#define MINISQL_OK           0
#define MINISQL_ERROR        1
#define MINISQL_IOERR        2
#define MINISQL_NOTFOUND     3
#define MINISQL_DUPLICATE    4
#define MINISQL_BUSY         5
#define MINISQL_NOMEM        6
#define MINISQL_INVALID      7
#define MINISQL_MISMATCH     8

// 数据类型
#define MINISQL_TYPE_NULL    0
#define MINISQL_TYPE_INT     1
#define MINISQL_TYPE_TEXT    2

// 操作码
#define OP_NONE              0
#define OP_CREATE_TABLE      1
#define OP_INSERT            2
#define OP_SELECT            3
#define OP_DELETE            4
#define OP_UPDATE            5
#define OP_BEGIN             6
#define OP_COMMIT            7
#define OP_ROLLBACK          8
#define OP_CREATE_INDEX      9

// 事务状态
#define TX_STATUS_INACTIVE   0
#define TX_STATUS_ACTIVE     1
#define TX_STATUS_COMMITTED  2
#define TX_STATUS_ROLLEDBACK 3

// B树阶数
#define BTree_ORDER 8

// 最大标识符长度
#define MAX_IDENTIFIER_LEN  128
// 最大SQL语句长度
#define MAX_SQL_LENGTH      4096
// 最大列数
#define MAX_COLUMNS         32
// 最大表名长度
#define MAX_TABLE_NAME      128
// 最大列名长度
#define MAX_COLUMN_NAME     128

// 向前声明
typedef struct MiniSQL MiniSQL;
typedef struct Table Table;
typedef struct Column Column;
typedef struct Row Row;
typedef struct Value Value;
typedef struct BTreeNode BTreeNode;
typedef struct BTreeIndex BTreeIndex;
typedef struct Transaction Transaction;
typedef struct Statement Statement;
typedef struct ResultSet ResultSet;
typedef struct Token Token;
typedef struct UndoLogEntry UndoLogEntry;

// 值结构
typedef struct Value {
    int type;
    union {
        int64_t i;
        char* s;
    } as;
} Value;

// 列定义
typedef struct Column {
    char name[MAX_COLUMN_NAME];
    int type;
    int is_primary;
} Column;

// 行数据
typedef struct Row {
    int64_t row_id;
    Value* values;
    struct Row* next;
    struct Row* prev;
} Row;

// B树节点
typedef struct BTreeNode {
    int n_keys;
    int64_t keys[BTree_ORDER];
    int64_t row_ids[BTree_ORDER];
    struct BTreeNode* children[BTree_ORDER + 1];
    int is_leaf;
} BTreeNode;

// B树索引
typedef struct BTreeIndex {
    char table_name[MAX_TABLE_NAME];
    char column_name[MAX_COLUMN_NAME];
    BTreeNode* root;
    struct BTreeIndex* next;
} BTreeIndex;

// 表结构
typedef struct Table {
    char name[MAX_TABLE_NAME];
    Column columns[MAX_COLUMNS];
    int column_count;
    Row* rows;
    int row_count;
    int64_t next_row_id;
    struct Table* next;
} Table;

// 撤销日志条目
typedef struct UndoLogEntry {
    int op;
    char table_name[MAX_TABLE_NAME];
    int64_t row_id;
    Row* old_row;  // 用于UPDATE和DELETE
    struct UndoLogEntry* next;
} UndoLogEntry;

// 事务
typedef struct Transaction {
    int status;
    UndoLogEntry* undo_log;
} Transaction;

// 解析器令牌类型（重命名避免冲突）
typedef enum {
    TOKEN_EOF,
    TOKEN_SELECT,
    TOKEN_INSERT,
    TOKEN_UPDATE,
    TOKEN_DELETE,
    TOKEN_CREATE,
    TOKEN_TABLE,
    TOKEN_INDEX,
    TOKEN_ON,
    TOKEN_INTO,
    TOKEN_VALUES,
    TOKEN_FROM,
    TOKEN_WHERE,
    TOKEN_SET,
    TOKEN_AND,
    TOKEN_OR,
    TOKEN_NOT,
    TOKEN_EQ,
    TOKEN_NE,
    TOKEN_LT,
    TOKEN_GT,
    TOKEN_LE,
    TOKEN_GE,
    TOKEN_LPAREN,
    TOKEN_RPAREN,
    TOKEN_COMMA,
    TOKEN_SEMICOLON,
    TOKEN_DOT,
    TOKEN_ASTERISK,
    TOKEN_INT,
    TOKEN_TEXT,
    TOKEN_NULL,
    TOKEN_IDENTIFIER,
    TOKEN_STRING,
    TOKEN_NUMBER,
    TOKEN_BEGIN,
    TOKEN_COMMIT,
    TOKEN_ROLLBACK,
    TOKEN_PRIMARY,
    TOKEN_KEY
} MiniSqlTokenType;

typedef struct Token {
    MiniSqlTokenType type;
    char value[MAX_SQL_LENGTH];
    int line;
    int pos;
} Token;

// 条件表达式
typedef struct Expr {
    char column[MAX_COLUMN_NAME];
    int op;  // 比较操作: EQ, NE, LT, GT, LE, GE
    Value value;
    struct Expr* left;
    struct Expr* right;
    int is_and;  // 1 if AND, 0 if OR
} Expr;

// 语句结构
typedef struct Statement {
    int type;
    char table_name[MAX_TABLE_NAME];
    
    // 用于SELECT
    char columns[MAX_COLUMNS][MAX_COLUMN_NAME];
    int column_count;
    int select_all;
    Expr* where_clause;
    
    // 用于INSERT
    Value values[MAX_COLUMNS];
    int value_count;
    
    // 用于UPDATE
    char update_columns[MAX_COLUMNS][MAX_COLUMN_NAME];
    Value update_values[MAX_COLUMNS];
    int update_count;
    
    // 用于CREATE TABLE
    Column create_columns[MAX_COLUMNS];
    int create_column_count;
    
    // 用于CREATE INDEX
    char index_column[MAX_COLUMN_NAME];
} Statement;

// 结果集
typedef struct ResultSet {
    Table* table;
    Row** rows;
    int row_count;
    int column_count;
    char columns[MAX_COLUMNS][MAX_COLUMN_NAME];
} ResultSet;

#if 0
// 数据库主结构
typedef struct MiniSQL {
    char db_path[PATH_MAX];
    Table* tables;
    BTreeIndex* indexes;
    Transaction tx;
    char* err_msg;
    int is_open;
} MiniSQL;
#endif

// 数据库主结构
typedef struct MiniSQL {
    char db_path[PATH_MAX];
    char lock_path[PATH_MAX];  // 新增：锁文件路径
#ifdef _WIN32
    HANDLE lock_handle;        // 新增：Windows 锁文件句柄
#else
    int lock_fd;               // 新增：Linux/Unix 锁文件描述符
#endif
    Table* tables;
    BTreeIndex* indexes;
    Transaction tx;
    char* err_msg;
    int is_open;
} MiniSQL;

// 公共API
MiniSQL* minisql_open(const char* path);
int minisql_close(MiniSQL* db);
int minisql_exec(MiniSQL* db, const char* sql, ResultSet** result);
void minisql_free_result(ResultSet* result);
const char* minisql_errmsg(MiniSQL* db);
void minisql_repl(MiniSQL* db);

// 内部函数声明
static void set_error(MiniSQL* db, const char* fmt, ...);
static Table* find_table(MiniSQL* db, const char* name);
static int create_table(MiniSQL* db, const char* name, Column* columns, int column_count);
static int insert_row(MiniSQL* db, const char* table_name, Value* values, int value_count);
static ResultSet* select_rows(MiniSQL* db, const char* table_name, const char** columns, int column_count, int select_all, Expr* where);
static int delete_rows(MiniSQL* db, const char* table_name, Expr* where);
static int update_rows(MiniSQL* db, const char* table_name, char** columns, Value* values, int count, Expr* where);
static int create_index(MiniSQL* db, const char* name, const char* table_name, const char* column_name);
static int begin_transaction(MiniSQL* db);
static int commit_transaction(MiniSQL* db);
static int rollback_transaction(MiniSQL* db);
static int save_to_disk(MiniSQL* db);
static int load_from_disk(MiniSQL* db);

// 令牌解析函数
static Token sql_next_token(const char** sql, int* line, int* pos);
static int parse_statement(MiniSQL* db, const char* sql, Statement* stmt);
static int parse_select(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos);
static int parse_insert(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos);
static int parse_delete(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos);
static int parse_update(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos);
static int parse_create_table(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos);
static int parse_create_index(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos);
static int parse_where_clause(MiniSQL* db, const char** sql, Expr** expr, int* line, int* pos);
static int parse_expression(MiniSQL* db, const char** sql, Expr** expr, int* line, int* pos);
static int parse_value(MiniSQL* db, const char** sql, Value* value, int* line, int* pos);

// B树函数
static BTreeIndex* find_index(MiniSQL* db, const char* table_name, const char* column_name);
static BTreeNode* btree_create_node(int is_leaf);
static void btree_split_child(BTreeNode* parent, int index);
static void btree_insert_non_full(BTreeNode* node, int64_t key, int64_t row_id);
static int btree_insert(BTreeIndex* index, int64_t key, int64_t row_id);
static int btree_search(BTreeIndex* index, int64_t key, int64_t* row_id);
static void btree_free_node(BTreeNode* node);

// 事务和日志函数
static void add_undo_log(MiniSQL* db, int op, const char* table_name, int64_t row_id, Row* old_row);
static Row* copy_row(Row* row, int column_count);
static void free_row(Row* row, int column_count);

// 辅助函数
static int evaluate_expression(Row* row, Table* table, Expr* expr);
static int compare_values(Value* a, Value* b);
static void free_expr(Expr* expr);
static int column_index(Table* table, const char* column_name);
static Row* find_row_by_id(Table* table, int64_t row_id);
static Row** find_rows_by_condition(Table* table, Expr* where, int* count);
static int binary_search_rows(Row** rows, int count, int column_idx, Value* value, int op);

// Windows兼容的getline实现
#ifdef _WIN32
static ssize_t getline(char**lineptr, size_t* n, FILE* stream) {
    if (*lineptr == NULL || *n == 0) {
        *n = 1024;
        *lineptr = (char*)malloc(*n);
        if (*lineptr == NULL) return -1;
    }

    ssize_t i = 0;
    int c;
    while ((c = fgetc(stream)) != EOF && c != '\n') {
        if (i + 1 >= (ssize_t)*n) {
            *n *= 2;
            char* new_ptr = (char*)realloc(*lineptr, *n);
            if (new_ptr == NULL) return -1;
            *lineptr = new_ptr;
        }
        (*lineptr)[i++] = (char)c;
    }

    if (c == EOF && i == 0) return -1;

    (*lineptr)[i] = '\0';
    return i;
}
#endif

#ifdef MINISQL_IMPLEMENTATION

// 错误处理
static void set_error(MiniSQL* db, const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    
    if (db->err_msg) free(db->err_msg);
    db->err_msg = (char*)malloc(1024);
    vsnprintf(db->err_msg, 1023, fmt, args);
    
    va_end(args);
}

#if 0
// 打开数据库
MiniSQL* minisql_open(const char* path) {
    MiniSQL* db = (MiniSQL*)malloc(sizeof(MiniSQL));
    if (!db) return NULL;
    
    memset(db, 0, sizeof(MiniSQL));
    strncpy(db->db_path, path, PATH_MAX - 1);
    db->err_msg = NULL;
    db->tables = NULL;
    db->indexes = NULL;
    db->tx.status = TX_STATUS_INACTIVE;
    db->tx.undo_log = NULL;
    
    // 创建数据库目录（如果不存在）
#ifdef _WIN32
    char dir[PATH_MAX];
    strncpy(dir, path, PATH_MAX - 1);
    char* last_slash = strrchr(dir, '\\');
    if (last_slash) {
        *last_slash = '\0';
        CreateDirectoryA(dir, NULL);
    }
#else
    char dir[PATH_MAX];
    strncpy(dir, path, PATH_MAX - 1);
    char* last_slash = strrchr(dir, '/');
    if (last_slash) {
        *last_slash = '\0';
        mkdir(dir, 0755);
    }
#endif
    
    // 尝试从磁盘加载
    if (load_from_disk(db) != MINISQL_OK) {
        // 如果加载失败，初始化新数据库
        db->is_open = 1;
    }
    
    return db;
}
#endif

// 打开数据库 - 增加文件锁机制防止多实例访问
MiniSQL* minisql_open(const char* path) {
    if (!path || !*path) {
        fprintf(stderr, "错误：数据库路径不能为空\n");
        return NULL;
    }

    // 生成锁文件路径
    char lock_path[PATH_MAX];
    snprintf(lock_path, PATH_MAX, "%s.lock", path);

    // 检查并创建锁文件
    int lock_fd = -1;
#ifdef _WIN32
    // Windows平台使用文件锁定
    HANDLE hFile = CreateFileA(lock_path, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_HIDDEN, NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
        // 如果文件已存在，说明已有实例在运行
        fprintf(stderr, "错误：数据库已被其他实例打开，请先关闭该实例\n");
        return NULL;
    }
#else
    // Linux/Unix平台使用fcntl锁定
    lock_fd = open(lock_path, O_CREAT | O_EXCL | O_WRONLY, 0600);
    if (lock_fd == -1) {
        if (errno == EEXIST) {
            fprintf(stderr, "错误：数据库已被其他实例打开，请先关闭该实例\n");
            return NULL;
        } else {
            fprintf(stderr, "错误：无法创建锁文件: %s\n", strerror(errno));
            return NULL;
        }
    }
#endif

    // 分配数据库结构
    MiniSQL* db = (MiniSQL*)malloc(sizeof(MiniSQL));
    if (!db) {
        fprintf(stderr, "错误：内存分配失败\n");
#ifdef _WIN32
        CloseHandle(hFile);
        DeleteFileA(lock_path);
#else
        close(lock_fd);
        unlink(lock_path);
#endif
        return NULL;
    }
    
    memset(db, 0, sizeof(MiniSQL));
    strncpy(db->db_path, path, PATH_MAX - 1);
    // 保存锁文件路径，用于关闭时清理
    strncpy(db->lock_path, lock_path, PATH_MAX - 1);
    db->err_msg = NULL;
    db->tables = NULL;
    db->indexes = NULL;
    db->tx.status = TX_STATUS_INACTIVE;
    db->tx.undo_log = NULL;
    db->is_open = 0;
#ifdef _WIN32
    db->lock_handle = hFile;
#else
    db->lock_fd = lock_fd;
#endif

    // 创建数据库目录（如果不存在）
#ifdef _WIN32
    char dir[PATH_MAX];
    strncpy(dir, path, PATH_MAX - 1);
    char* last_slash = strrchr(dir, '\\');
    if (last_slash) {
        *last_slash = '\0';
        CreateDirectoryA(dir, NULL);
    }
#else
    char dir[PATH_MAX];
    strncpy(dir, path, PATH_MAX - 1);
    char* last_slash = strrchr(dir, '/');
    if (last_slash) {
        *last_slash = '\0';
        mkdir(dir, 0755);
    }
#endif
    
    // 尝试从磁盘加载数据库
    int rc = load_from_disk(db);
    if (rc != MINISQL_OK) {
        // 加载失败时初始化新数据库
        #ifdef HAS_COLOR_PRINT
        cprintf("注意：未找到现有数据库，将创建新数据库\n");
        #else
        printf("注意：未找到现有数据库，将创建新数据库\n");
        #endif
        db->is_open = 1;
    } else {
        db->is_open = 1;
        #ifdef HAS_COLOR_PRINT
        cprintf("数据库打开成功\n");
        #else
        printf("数据库打开成功\n");
        #endif
    }
    
    return db;
}

#if 0
// 关闭数据库
int minisql_close(MiniSQL* db) {
    if (!db || !db->is_open) return MINISQL_ERROR;
    
    // 保存到磁盘
    save_to_disk(db);
    
    // 释放表
    Table* table = db->tables;
    while (table) {
        Table* next = table->next;
        
        // 释放行
        Row* row = table->rows;
        while (row) {
            Row* next_row = row->next;
            
            // 释放值
            for (int i = 0; i < table->column_count; i++) {
                if (row->values[i].type == MINISQL_TYPE_TEXT) {
                    free(row->values[i].as.s);
                }
            }
            free(row->values);
            free(row);
            
            row = next_row;
        }
        
        free(table);
        table = next;
    }
    
    // 释放索引
    BTreeIndex* index = db->indexes;
    while (index) {
        BTreeIndex* next = index->next;
        if (index->root) {
            btree_free_node(index->root);
        }
        free(index);
        index = next;
    }
    
    // 释放错误消息
    if (db->err_msg) free(db->err_msg);
    
    free(db);
    return MINISQL_OK;
}
#endif

// 关闭数据库 - 增加锁文件清理
int minisql_close(MiniSQL* db) {
    if (!db || !db->is_open) {
        fprintf(stderr, "\n错误：数据库未打开或指针为空\n");
        return MINISQL_ERROR;
    }
    
    // 保存数据到磁盘
    int save_rc = save_to_disk(db);
    if (save_rc != MINISQL_OK) {
        fprintf(stderr, "\n警告：保存数据库到磁盘时发生错误\n");
    }
    
    // 释放表资源
    Table* table = db->tables;
    while (table) {
        Table* next = table->next;
        
        // 释放行数据
        Row* row = table->rows;
        while (row) {
            Row* next_row = row->next;
            
            // 释放值数据，特别是文本类型
            for (int i = 0; i < table->column_count; i++) {
                if (row->values[i].type == MINISQL_TYPE_TEXT) {
                    free(row->values[i].as.s);
                }
            }
            free(row->values);
            free(row);
            
            row = next_row;
        }
        
        free(table);
        table = next;
    }
    
    // 释放索引
    BTreeIndex* index = db->indexes;
    while (index) {
        BTreeIndex* next = index->next;
        if (index->root) {
            btree_free_node(index->root);
        }
        free(index);
        index = next;
    }
    
    // 释放事务日志
    UndoLogEntry* entry = db->tx.undo_log;
    while (entry) {
        UndoLogEntry* next = entry->next;
        if (entry->old_row) {
            Table* t = find_table(db, entry->table_name);
            if (t) free_row(entry->old_row, t->column_count);
        }
        free(entry);
        entry = next;
    }
    
    // 释放错误消息
    if (db->err_msg) {
        free(db->err_msg);
        db->err_msg = NULL;
    }
    
    // 释放锁文件
#ifdef _WIN32
    CloseHandle(db->lock_handle);
    DeleteFileA(db->lock_path);
#else
    close(db->lock_fd);
    unlink(db->lock_path);
#endif

    db->is_open = 0;
    free(db);
    #ifdef  HAS_COLOR_PRINT
    cprintf("\n数据库已成功关闭\n");
    #else
    printf("\n数据库已成功关闭\n");
    #endif
    return (save_rc == MINISQL_OK) ? MINISQL_OK : MINISQL_IOERR;
}


// 查找表
static Table* find_table(MiniSQL* db, const char* name) {
    Table* table = db->tables;
    while (table) {
        if (strcmp(table->name, name) == 0) {
            return table;
        }
        table = table->next;
    }
    return NULL;
}

// 创建表
static int create_table(MiniSQL* db, const char* name, Column* columns, int column_count) {
    if (find_table(db, name)) {
        set_error(db, "Table '%s' already exists", name);
        return MINISQL_DUPLICATE;
    }
    
    Table* table = (Table*)malloc(sizeof(Table));
    if (!table) {
        set_error(db, "Out of memory");
        return MINISQL_NOMEM;
    }
    
    strncpy(table->name, name, MAX_TABLE_NAME - 1);
    table->column_count = column_count;
    memcpy(table->columns, columns, column_count * sizeof(Column));
    table->rows = NULL;
    table->row_count = 0;
    table->next_row_id = 1;
    table->next = db->tables;
    db->tables = table;
    
    // 如果有事务活动，记录日志
    if (db->tx.status == TX_STATUS_ACTIVE) {
        add_undo_log(db, OP_CREATE_TABLE, name, 0, NULL);
    }
    
    return MINISQL_OK;
}

// 复制行
static Row* copy_row(Row* row, int column_count) {
    if (!row) return NULL;
    
    Row* new_row = (Row*)malloc(sizeof(Row));
    if (!new_row) return NULL;
    
    new_row->row_id = row->row_id;
    new_row->values = (Value*)malloc(column_count * sizeof(Value));
    if (!new_row->values) {
        free(new_row);
        return NULL;
    }
    
    for (int i = 0; i < column_count; i++) {
        new_row->values[i].type = row->values[i].type;
        switch (row->values[i].type) {
            case MINISQL_TYPE_INT:
                new_row->values[i].as.i = row->values[i].as.i;
                break;
            case MINISQL_TYPE_TEXT:
                new_row->values[i].as.s = strdup(row->values[i].as.s);
                break;
            default:
                break;
        }
    }
    
    new_row->next = NULL;
    new_row->prev = NULL;
    return new_row;
}

// 释放行
static void free_row(Row* row, int column_count) {
    if (!row) return;
    
    for (int i = 0; i < column_count; i++) {
        if (row->values[i].type == MINISQL_TYPE_TEXT) {
            free(row->values[i].as.s);
        }
    }
    free(row->values);
    free(row);
}

// 添加撤销日志条目
static void add_undo_log(MiniSQL* db, int op, const char* table_name, int64_t row_id, Row* old_row) {
    if (db->tx.status != TX_STATUS_ACTIVE) return;
    
    UndoLogEntry* entry = (UndoLogEntry*)malloc(sizeof(UndoLogEntry));
    if (!entry) return;
    
    entry->op = op;
    strncpy(entry->table_name, table_name, MAX_TABLE_NAME - 1);
    entry->row_id = row_id;
    entry->old_row = old_row;  // 调用者负责复制行
    entry->next = db->tx.undo_log;
    db->tx.undo_log = entry;
}

// 插入行
static int insert_row(MiniSQL* db, const char* table_name, Value* values, int value_count) {
    Table* table = find_table(db, table_name);
    if (!table) {
        set_error(db, "Table '%s' not found", table_name);
        return MINISQL_NOTFOUND;
    }
    
    if (value_count != table->column_count) {
        set_error(db, "Column count mismatch: expected %d, got %d", table->column_count, value_count);
        return MINISQL_MISMATCH;
    }
    
    // 检查主键唯一性
    // 在 insert_row 函数中，添加主键唯一性检查（在“检查主键唯一性”部分替换原逻辑）
    for (int col_idx = 0; col_idx < table->column_count; col_idx++) {
        // 找到主键列
        if (table->columns[col_idx].is_primary) {
            // 待插入的主键值
            Value* new_val = &values[col_idx];
            if (new_val->type == MINISQL_TYPE_NULL) {
                set_error(db, "Primary key cannot be NULL");
                return MINISQL_INVALID;
            }

            // 遍历表中所有行，检查是否有重复的主键值
            Row* existing_row = table->rows;
            while (existing_row) {
                Value* existing_val = &existing_row->values[col_idx];
                if (compare_values(new_val, existing_val) == 0) {
                    set_error(db, "Primary key violation: duplicate value for column '%s'", 
                            table->columns[col_idx].name);
                    return MINISQL_DUPLICATE;
                }
                existing_row = existing_row->next;
            }
        }
    }
    
    // 创建新行
    Row* row = (Row*)malloc(sizeof(Row));
    if (!row) {
        set_error(db, "Out of memory");
        return MINISQL_NOMEM;
    }
    
    row->row_id = table->next_row_id++;
    row->values = (Value*)malloc(table->column_count * sizeof(Value));
    if (!row->values) {
        free(row);
        set_error(db, "Out of memory");
        return MINISQL_NOMEM;
    }
    
    // 复制值
    for (int i = 0; i < table->column_count; i++) {
        row->values[i].type = values[i].type;
        switch (values[i].type) {
            case MINISQL_TYPE_INT:
                row->values[i].as.i = values[i].as.i;
                break;
            case MINISQL_TYPE_TEXT:
                row->values[i].as.s = strdup(values[i].as.s);
                break;
            default:
                break;
        }
    }
    
    // 添加到表的行链表
    row->next = table->rows;
    row->prev = NULL;
    if (table->rows) {
        table->rows->prev = row;
    }
    table->rows = row;
    table->row_count++;
    
    // 更新索引
    BTreeIndex* index = db->indexes;
    while (index) {
        if (strcmp(index->table_name, table_name) == 0) {
            int col_idx = column_index(table, index->column_name);
            if (col_idx != -1 && row->values[col_idx].type == MINISQL_TYPE_INT) {
                btree_insert(index, row->values[col_idx].as.i, row->row_id);
            }
        }
        index = index->next;
    }
    
    // 记录撤销日志
    if (db->tx.status == TX_STATUS_ACTIVE) {
        add_undo_log(db, OP_INSERT, table_name, row->row_id, NULL);
    }
    
    return MINISQL_OK;
}

// 查找列索引
static int column_index(Table* table, const char* column_name) {
    for (int i = 0; i < table->column_count; i++) {
        if (strcmp(table->columns[i].name, column_name) == 0) {
            return i;
        }
    }
    return -1;
}

// 查找行通过ID
static Row* find_row_by_id(Table* table, int64_t row_id) {
    Row* row = table->rows;
    while (row) {
        if (row->row_id == row_id) {
            return row;
        }
        row = row->next;
    }
    return NULL;
}

// 比较值
static int compare_values(Value* a, Value* b) {
    if (a->type != b->type) return -2;  // 类型不匹配
    
    switch (a->type) {
        case MINISQL_TYPE_INT:
            if (a->as.i < b->as.i) return -1;
            if (a->as.i > b->as.i) return 1;
            return 0;
        case MINISQL_TYPE_TEXT:
            return strcmp(a->as.s, b->as.s);
        default:
            return 0;
    }
}

// 评估表达式
static int evaluate_expression(Row* row, Table* table, Expr* expr) {
    if (!expr) return 1;  // 没有条件，匹配所有行
    
    if (expr->left && expr->right) {
        int left_res = evaluate_expression(row, table, expr->left);
        int right_res = evaluate_expression(row, table, expr->right);
        return expr->is_and ? (left_res && right_res) : (left_res || right_res);
    }
    
    int col_idx = column_index(table, expr->column);
    if (col_idx == -1) return 0;
    
    Value* row_val = &row->values[col_idx];
    Value* cond_val = &expr->value;
    
    int cmp = compare_values(row_val, cond_val);
    if (cmp == -2) return 0;  // 类型不匹配
    
    switch (expr->op) {
        case TOKEN_EQ: return cmp == 0;
        case TOKEN_NE: return cmp != 0;
        case TOKEN_LT: return cmp < 0;
        case TOKEN_GT: return cmp > 0;
        case TOKEN_LE: return cmp <= 0;
        case TOKEN_GE: return cmp >= 0;
        default: return 0;
    }
}

// 查找满足条件的行
static Row** find_rows_by_condition(Table* table, Expr* where, int* count) {
    *count = 0;
    if (!table || !table->rows) return NULL;
    
    // 先计算匹配的行数
    Row* row = table->rows;
    while (row) {
        if (evaluate_expression(row, table, where)) {
            (*count)++;
        }
        row = row->next;
    }
    
    if (*count == 0) return NULL;
    
    // 分配结果数组
    Row** result = (Row**)malloc(*count * sizeof(Row*));
    if (!result) return NULL;
    
    // 填充结果数组
    int idx = 0;
    row = table->rows;
    while (row) {
        if (evaluate_expression(row, table, where)) {
            result[idx++] = row;
        }
        row = row->next;
    }
    
    return result;
}

// 二分查找行
static int binary_search_rows(Row** rows, int count, int column_idx, Value* value, int op) {
    if (count == 0 || !rows || value->type != MINISQL_TYPE_INT) return -1;
    
    int left = 0, right = count - 1;
    int64_t target = value->as.i;
    
    while (left <= right) {
        int mid = left + (right - left) / 2;
        int64_t val = rows[mid]->values[column_idx].as.i;
        
        if (val == target) {
            if (op == TOKEN_EQ || op == TOKEN_LE || op == TOKEN_GE) {
                return mid;
            }
            break;
        } else if (val < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    // 根据操作返回适当的索引
    switch (op) {
        case TOKEN_LT: return right;
        case TOKEN_GT: return left;
        case TOKEN_LE: return right;
        case TOKEN_GE: return left;
        default: return -1;
    }
}


static ResultSet* select_rows(MiniSQL* db, const char* table_name, const char** columns, int column_count, int select_all, Expr* where) {
    Table* table = find_table(db, table_name);
    if (!table) {
        set_error(db, "Table '%s' not found", table_name);
        return NULL;
    }
    
    // 确定要返回的列（修复select *逻辑）
    char result_columns[MAX_COLUMNS][MAX_COLUMN_NAME];
    int result_column_count = 0;
    
    if (select_all) {
        // 关键修复：确保遍历所有列并复制列名
        for (int i = 0; i < table->column_count; i++) {
            // 跳过空列名（避免无效列）
            if (table->columns[i].name[0] != '\0') {
                strncpy(result_columns[result_column_count++], table->columns[i].name, MAX_COLUMN_NAME - 1);
            }
        }
        // 极端情况：表无有效列时提示
        if (result_column_count == 0) {
            set_error(db, "Table '%s' has no valid columns", table_name);
            free_expr(where);
            return NULL;
        }
    } else {
        // 处理指定列（原有逻辑不变）
        for (int i = 0; i < column_count; i++) {
            int found = 0;
            for (int j = 0; j < table->column_count; j++) {
                if (strcmp(columns[i], table->columns[j].name) == 0) {
                    strncpy(result_columns[result_column_count++], columns[i], MAX_COLUMN_NAME - 1);
                    found = 1;
                    break;
                }
            }
            if (!found) {
                set_error(db, "Column '%s' not found in table '%s'", columns[i], table_name);
                free_expr(where);
                return NULL;
            }
        }
    }
    
    // 查找满足条件的行（原有逻辑不变）
    int row_count;
    Row** matching_rows = find_rows_by_condition(table, where, &row_count);
    if (!matching_rows && row_count > 0) {
        set_error(db, "Out of memory");
        free_expr(where);
        return NULL;
    }
    
    // 创建结果集（原有逻辑不变）
    ResultSet* result = (ResultSet*)malloc(sizeof(ResultSet));
    if (!result) {
        set_error(db, "Out of memory");
        free(matching_rows);
        free_expr(where);
        return NULL;
    }
    
    result->table = table;
    result->rows = matching_rows;
    result->row_count = row_count;
    result->column_count = result_column_count;
    memcpy(result->columns, result_columns, result_column_count * MAX_COLUMN_NAME);
    
    free_expr(where);
    return result;
}

// 删除行
static int delete_rows(MiniSQL* db, const char* table_name, Expr* where) {
    Table* table = find_table(db, table_name);
    if (!table) {
        set_error(db, "Table '%s' not found", table_name);
        free_expr(where);
        return MINISQL_NOTFOUND;
    }
    
    // 查找要删除的行
    int row_count;
    Row** rows_to_delete = find_rows_by_condition(table, where, &row_count);
    if (!rows_to_delete && row_count > 0) {
        set_error(db, "Out of memory");
        free_expr(where);
        return MINISQL_NOMEM;
    }
    
    // 如果有事务活动，记录日志
    if (db->tx.status == TX_STATUS_ACTIVE) {
        for (int i = 0; i < row_count; i++) {
            Row* old_row = copy_row(rows_to_delete[i], table->column_count);
            add_undo_log(db, OP_DELETE, table_name, rows_to_delete[i]->row_id, old_row);
        }
    }
    
    // 执行删除
    for (int i = 0; i < row_count; i++) {
        Row* row = rows_to_delete[i];
        
        // 从链表中移除
        if (row->prev) {
            row->prev->next = row->next;
        } else {
            table->rows = row->next;  // 更新表头
        }
        
        if (row->next) {
            row->next->prev = row->prev;
        }
        
        // 释放行数据
        for (int j = 0; j < table->column_count; j++) {
            if (row->values[j].type == MINISQL_TYPE_TEXT) {
                free(row->values[j].as.s);
            }
        }
        free(row->values);
        free(row);
        
        table->row_count--;
    }
    
    free(rows_to_delete);
    free_expr(where);
    return MINISQL_OK;
}

// 更新行
static int update_rows(MiniSQL* db, const char* table_name, char** columns, Value* values, int count, Expr* where) {
    Table* table = find_table(db, table_name);
    if (!table) {
        set_error(db, "Table '%s' not found", table_name);
        return MINISQL_NOTFOUND;
    }

    // 1. 验证列存在性
    int col_indices[MAX_COLUMNS];
    for (int i = 0; i < count; i++) {
        col_indices[i] = column_index(table, columns[i]);
        if (col_indices[i] == -1) {
            set_error(db, "Column '%s' not found", columns[i]);
            return MINISQL_NOTFOUND;
        }
    }

    // 2. 查找符合WHERE条件的行（关键修复：过滤行）
    int match_count;
    Row** rows_to_update = find_rows_by_condition(table, where, &match_count);
    if (!rows_to_update && match_count > 0) {
        set_error(db, "Out of memory");
        return MINISQL_NOMEM;
    }

    // 3. 仅更新符合条件的行（而非全表）
    for (int i = 0; i < match_count; i++) {
        Row* row = rows_to_update[i];
        // 更新行数据
        for (int j = 0; j < count; j++) {
            int col_idx = col_indices[j];
            // 释放旧值（文本类型）
            if (row->values[col_idx].type == MINISQL_TYPE_TEXT) {
                free(row->values[col_idx].as.s);
            }
            // 设置新值
            row->values[col_idx].type = values[j].type;
            switch (values[j].type) {
                case MINISQL_TYPE_INT:
                    row->values[col_idx].as.i = values[j].as.i;
                    break;
                case MINISQL_TYPE_TEXT:
                    row->values[col_idx].as.s = strdup(values[j].as.s);
                    break;
            }
        }
    }

    free(rows_to_update);
    return MINISQL_OK;
}

// 开始事务
static int begin_transaction(MiniSQL* db) {
    if (db->tx.status == TX_STATUS_ACTIVE) {
        set_error(db, "Nested transactions not supported");
        return MINISQL_ERROR;
    }
    
    // 清除任何现有日志
    UndoLogEntry* entry = db->tx.undo_log;
    while (entry) {
        UndoLogEntry* next = entry->next;
        if (entry->old_row) {
            Table* table = find_table(db, entry->table_name);
            if (table) {
                free_row(entry->old_row, table->column_count);
            }
        }
        free(entry);
        entry = next;
    }
    
    db->tx.undo_log = NULL;
    db->tx.status = TX_STATUS_ACTIVE;
    return MINISQL_OK;
}

// 提交事务
static int commit_transaction(MiniSQL* db) {
    if (db->tx.status != TX_STATUS_ACTIVE) {
        set_error(db, "No active transaction");
        return MINISQL_ERROR;
    }
    
    // 释放撤销日志
    UndoLogEntry* entry = db->tx.undo_log;
    while (entry) {
        UndoLogEntry* next = entry->next;
        if (entry->old_row) {
            Table* table = find_table(db, entry->table_name);
            if (table) {
                free_row(entry->old_row, table->column_count);
            }
        }
        free(entry);
        entry = next;
    }
    
    db->tx.undo_log = NULL;
    db->tx.status = TX_STATUS_COMMITTED;
    
    // 提交时保存到磁盘
    save_to_disk(db);
    return MINISQL_OK;
}

// 回滚事务
static int rollback_transaction(MiniSQL* db) {
    if (db->tx.status != TX_STATUS_ACTIVE) {
        set_error(db, "No active transaction");
        return MINISQL_ERROR;
    }
    
    // 反向处理撤销日志
    UndoLogEntry* entry = db->tx.undo_log;
    while (entry) {
        Table* table = find_table(db, entry->table_name);
        if (table) {
            switch (entry->op) {
                case OP_INSERT: {
                    // 撤销插入：删除行
                    Row* row = find_row_by_id(table, entry->row_id);
                    if (row) {
                        // 从链表中移除
                        if (row->prev) row->prev->next = row->next;
                        else table->rows = row->next;
                        if (row->next) row->next->prev = row->prev;
                        
                        // 释放行
                        for (int i = 0; i < table->column_count; i++) {
                            if (row->values[i].type == MINISQL_TYPE_TEXT) {
                                free(row->values[i].as.s);
                            }
                        }
                        free(row->values);
                        free(row);
                        table->row_count--;
                    }
                    break;
                }
                case OP_DELETE: {
                    // 撤销删除：恢复行
                    if (entry->old_row) {
                        Row* new_row = copy_row(entry->old_row, table->column_count);
                        if (new_row) {
                            new_row->row_id = entry->row_id;
                            new_row->next = table->rows;
                            new_row->prev = NULL;
                            if (table->rows) table->rows->prev = new_row;
                            table->rows = new_row;
                            table->row_count++;
                        }
                    }
                    break;
                }
                case OP_UPDATE: {
                    // 撤销更新：恢复旧值
                    Row* row = find_row_by_id(table, entry->row_id);
                    if (row && entry->old_row) {
                        // 释放当前值
                        for (int i = 0; i < table->column_count; i++) {
                            if (row->values[i].type == MINISQL_TYPE_TEXT) {
                                free(row->values[i].as.s);
                            }
                        }
                        
                        // 恢复旧值
                        for (int i = 0; i < table->column_count; i++) {
                            row->values[i].type = entry->old_row->values[i].type;
                            switch (row->values[i].type) {
                                case MINISQL_TYPE_INT:
                                    row->values[i].as.i = entry->old_row->values[i].as.i;
                                    break;
                                case MINISQL_TYPE_TEXT:
                                    row->values[i].as.s = strdup(entry->old_row->values[i].as.s);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    break;
                }
                case OP_CREATE_TABLE: {
                    // 撤销创建表（简化处理）
                    break;
                }
            }
        }
        
        UndoLogEntry* next = entry->next;
        if (entry->old_row) {
            Table* t = find_table(db, entry->table_name);
            if (t) {
                free_row(entry->old_row, t->column_count);
            }
        }
        free(entry);
        entry = next;
    }
    
    db->tx.undo_log = NULL;
    db->tx.status = TX_STATUS_ROLLEDBACK;
    return MINISQL_OK;
}

// 查找索引
static BTreeIndex* find_index(MiniSQL* db, const char* table_name, const char* column_name) {
    BTreeIndex* index = db->indexes;
    while (index) {
        if (strcmp(index->table_name, table_name) == 0 && 
            strcmp(index->column_name, column_name) == 0) {
            return index;
        }
        index = index->next;
    }
    return NULL;
}

// 创建B树节点
static BTreeNode* btree_create_node(int is_leaf) {
    BTreeNode* node = (BTreeNode*)malloc(sizeof(BTreeNode));
    if (!node) return NULL;
    
    node->n_keys = 0;
    node->is_leaf = is_leaf;
    memset(node->keys, 0, sizeof(node->keys));
    memset(node->row_ids, 0, sizeof(node->row_ids));
    memset(node->children, 0, sizeof(node->children));
    
    return node;
}

// 分裂子节点
static void btree_split_child(BTreeNode* parent, int index) {
    BTreeNode* child = parent->children[index];
    BTreeNode* new_node = btree_create_node(child->is_leaf);
    new_node->n_keys = BTree_ORDER / 2;
    
    // 复制后半部分键到新节点
    for (int i = 0; i < BTree_ORDER / 2; i++) {
        new_node->keys[i] = child->keys[i + BTree_ORDER / 2 + 1];
        new_node->row_ids[i] = child->row_ids[i + BTree_ORDER / 2 + 1];
    }
    
    // 如果不是叶子节点，复制子节点
    if (!child->is_leaf) {
        for (int i = 0; i < BTree_ORDER / 2 + 1; i++) {
            new_node->children[i] = child->children[i + BTree_ORDER / 2 + 1];
        }
    }
    
    child->n_keys = BTree_ORDER / 2;
    
    // 移动父节点的子节点指针
    for (int i = parent->n_keys; i > index; i--) {
        parent->children[i + 1] = parent->children[i];
    }
    parent->children[index + 1] = new_node;
    
    // 移动父节点的键
    for (int i = parent->n_keys - 1; i >= index; i--) {
        parent->keys[i + 1] = parent->keys[i];
        parent->row_ids[i + 1] = parent->row_ids[i];
    }
    
    // 提升中间键到父节点
    parent->keys[index] = child->keys[BTree_ORDER / 2];
    parent->row_ids[index] = child->row_ids[BTree_ORDER / 2];
    parent->n_keys++;
}

// 非满节点插入
static void btree_insert_non_full(BTreeNode* node, int64_t key, int64_t row_id) {
    int i = node->n_keys - 1;
    
    if (node->is_leaf) {
        // 叶子节点，直接插入
        while (i >= 0 && key < node->keys[i]) {
            node->keys[i + 1] = node->keys[i];
            node->row_ids[i + 1] = node->row_ids[i];
            i--;
        }
        node->keys[i + 1] = key;
        node->row_ids[i + 1] = row_id;
        node->n_keys++;
    } else {
        // 内部节点，找到子节点
        while (i >= 0 && key < node->keys[i]) {
            i--;
        }
        i++;
        
        // 检查子节点是否满
        if (node->children[i]->n_keys == BTree_ORDER) {
            // 分裂子节点
            btree_split_child(node, i);
            
            // 确定插入到哪个子节点
            if (key > node->keys[i]) {
                i++;
            }
        }
        
        // 递归插入到子节点
        btree_insert_non_full(node->children[i], key, row_id);
    }
}

// 插入键到B树
static int btree_insert(BTreeIndex* index, int64_t key, int64_t row_id) {
    if (!index) return MINISQL_INVALID;
    
    BTreeNode* root = index->root;
    
    // 如果根节点满，创建新根
    if (root->n_keys == BTree_ORDER) {
        BTreeNode* new_root = btree_create_node(0);
        index->root = new_root;
        new_root->children[0] = root;
        btree_split_child(new_root, 0);
        btree_insert_non_full(new_root, key, row_id);
    } else {
        btree_insert_non_full(root, key, row_id);
    }
    
    return MINISQL_OK;
}

// 搜索B树
static int btree_search(BTreeIndex* index, int64_t key, int64_t* row_id) {
    if (!index || !index->root) return MINISQL_NOTFOUND;
    
    BTreeNode* node = index->root;
    while (1) {
        int i = 0;
        while (i < node->n_keys && key > node->keys[i]) {
            i++;
        }
        
        if (i < node->n_keys && key == node->keys[i]) {
            *row_id = node->row_ids[i];
            return MINISQL_OK;
        }
        
        if (node->is_leaf) {
            return MINISQL_NOTFOUND;
        }
        
        node = node->children[i];
    }
}

// 释放B树节点
static void btree_free_node(BTreeNode* node) {
    if (!node) return;
    
    // 如果不是叶子节点，递归释放子节点
    if (!node->is_leaf) {
        for (int i = 0; i <= node->n_keys; i++) {
            btree_free_node(node->children[i]);
        }
    }
    
    free(node);
}

// 创建索引
static int create_index(MiniSQL* db, const char* name, const char* table_name, const char* column_name) {
    Table* table = find_table(db, table_name);
    if (!table) {
        set_error(db, "Table '%s' not found", table_name);
        return MINISQL_NOTFOUND;
    }
    
    // 检查列是否存在
    int col_idx = column_index(table, column_name);
    if (col_idx == -1) {
        set_error(db, "Column '%s' not found in table '%s'", column_name, table_name);
        return MINISQL_NOTFOUND;
    }
    
    // 检查列是否为整数类型（目前只支持整数索引）
    if (table->columns[col_idx].type != MINISQL_TYPE_INT) {
        set_error(db, "Index can only be created on integer columns");
        return MINISQL_ERROR;
    }
    
    // 检查索引是否已存在
    if (find_index(db, table_name, column_name)) {
        set_error(db, "Index on '%s.%s' already exists", table_name, column_name);
        return MINISQL_DUPLICATE;
    }
    
    // 创建新索引
    BTreeIndex* index = (BTreeIndex*)malloc(sizeof(BTreeIndex));
    if (!index) {
        set_error(db, "Out of memory");
        return MINISQL_NOMEM;
    }
    
    strncpy(index->table_name, table_name, MAX_TABLE_NAME - 1);
    strncpy(index->column_name, column_name, MAX_COLUMN_NAME - 1);
    index->root = btree_create_node(1);  // 初始为叶子节点
    index->next = db->indexes;
    db->indexes = index;
    
    // 为现有行创建索引条目
    Row* row = table->rows;
    while (row) {
        if (row->values[col_idx].type == MINISQL_TYPE_INT) {
            btree_insert(index, row->values[col_idx].as.i, row->row_id);
        }
        row = row->next;
    }
    
    // 记录事务日志
    if (db->tx.status == TX_STATUS_ACTIVE) {
        add_undo_log(db, OP_CREATE_INDEX, table_name, 0, NULL);
    }
    
    return MINISQL_OK;
}

// 释放表达式
static void free_expr(Expr* expr) {
    if (!expr) return;
    
    free_expr(expr->left);
    free_expr(expr->right);
    
    if (expr->value.type == MINISQL_TYPE_TEXT) {
        free(expr->value.as.s);
    }
    
    free(expr);
}

// 解析值
static int parse_value(MiniSQL* db, const char** sql, Value* value, int* line, int* pos) {
    const char* s = *sql;
    value->type = MINISQL_TYPE_NULL;
    
    // 跳过空格
    while (*s && isspace((unsigned char)*s)) {
        if (*s == '\n') (*line)++;
        else (*pos)++;
        s++;
    }
    
    if (!*s) return MINISQL_ERROR;
    
    // 字符串值
    if (*s == '\'') {
        s++; (*pos)++;
        const char* start = s;
        while (*s && *s != '\'') {
            if (*s == '\n') (*line)++;
            else (*pos)++;
            s++;
        }
        
        if (*s != '\'') {
            set_error(db, "Unclosed string literal at line %d, position %d", *line, *pos);
            return MINISQL_ERROR;
        }
        
        int len = s - start;
        value->type = MINISQL_TYPE_TEXT;
        value->as.s = (char*)malloc(len + 1);
        strncpy(value->as.s, start, len);
        value->as.s[len] = '\0';
        
        s++; (*pos)++;
        *sql = s;
        return MINISQL_OK;
    }
    
    // 数字值
    if (isdigit((unsigned char)*s) || *s == '-') {
        const char* start = s;
        if (*s == '-') {
            s++; (*pos)++;
            if (!isdigit((unsigned char)*s)) {
                set_error(db, "Invalid number format at line %d, position %d", *line, *pos);
                return MINISQL_ERROR;
            }
        }
        
        while (isdigit((unsigned char)*s)) {
            s++; (*pos)++;
        }
        
        // 只支持整数
        value->type = MINISQL_TYPE_INT;
        value->as.i = atoll(start);
        
        *sql = s;
        return MINISQL_OK;
    }
    
    // NULL值
    if (strncmp(s, "NULL", 4) == 0 && (s[4] == 0 || isspace((unsigned char)s[4]))) {
        value->type = MINISQL_TYPE_NULL;
        s += 4; *pos += 4;
        *sql = s;
        return MINISQL_OK;
    }
    
    set_error(db, "Unexpected token at line %d, position %d: %c", *line, *pos, *s);
    return MINISQL_ERROR;
}

#if 1
// 获取下一个令牌（重命名函数避免冲突）
// 获取下一个令牌（修复版）
static Token sql_next_token(const char** sql, int* line, int* pos) {
    Token token;
    memset(&token, 0, sizeof(Token));
    token.line = *line;
    token.pos = *pos;
    
    const char* s = *sql;
    
    // 跳过空格（修复空格计数逻辑）
    while (*s && isspace((unsigned char)*s)) {
        if (*s == '\n') {
            (*line)++;
            *pos = 0;  // 换行后重置列号为0
        } else {
            (*pos)++;  // 其他空格列号递增
        }
        s++;
    }
    
    if (!*s) {
        token.type = TOKEN_EOF;
        *sql = s;
        return token;
    }
    
    // 1. 标识符或关键字（字母或下划线开头）
    if (isalpha((unsigned char)*s) || *s == '_') {
        const char* start = s;
        // 收集完整标识符（字母、数字、下划线）
        while (isalnum((unsigned char)*s) || *s == '_') {
            s++;
            (*pos)++;
        }
        
        int len = s - start;
        strncpy(token.value, start, len);
        token.value[len] = '\0';  // 确保字符串终止
        
        // 关键字识别（不区分大小写）
        if (strcasecmp(token.value, "SELECT") == 0) token.type = TOKEN_SELECT;
        else if (strcasecmp(token.value, "INSERT") == 0) token.type = TOKEN_INSERT;
        else if (strcasecmp(token.value, "UPDATE") == 0) token.type = TOKEN_UPDATE;
        else if (strcasecmp(token.value, "DELETE") == 0) token.type = TOKEN_DELETE;
        else if (strcasecmp(token.value, "CREATE") == 0) token.type = TOKEN_CREATE;
        else if (strcasecmp(token.value, "TABLE") == 0) token.type = TOKEN_TABLE;
        else if (strcasecmp(token.value, "INDEX") == 0) token.type = TOKEN_INDEX;
        else if (strcasecmp(token.value, "ON") == 0) token.type = TOKEN_ON;
        else if (strcasecmp(token.value, "INTO") == 0) token.type = TOKEN_INTO;
        else if (strcasecmp(token.value, "VALUES") == 0) token.type = TOKEN_VALUES;
        else if (strcasecmp(token.value, "FROM") == 0) token.type = TOKEN_FROM;  // 确保FROM正确识别
        else if (strcasecmp(token.value, "WHERE") == 0) token.type = TOKEN_WHERE;  // 确保WHERE正确识别
        else if (strcasecmp(token.value, "SET") == 0) token.type = TOKEN_SET;  // 确保SET正确识别
        else if (strcasecmp(token.value, "AND") == 0) token.type = TOKEN_AND;
        else if (strcasecmp(token.value, "OR") == 0) token.type = TOKEN_OR;
        else if (strcasecmp(token.value, "NOT") == 0) token.type = TOKEN_NOT;
        else if (strcasecmp(token.value, "INT") == 0) token.type = TOKEN_INT;
        else if (strcasecmp(token.value, "TEXT") == 0) token.type = TOKEN_TEXT;
        else if (strcasecmp(token.value, "NULL") == 0) token.type = TOKEN_NULL;
        else if (strcasecmp(token.value, "BEGIN") == 0) token.type = TOKEN_BEGIN;
        else if (strcasecmp(token.value, "COMMIT") == 0) token.type = TOKEN_COMMIT;
        else if (strcasecmp(token.value, "ROLLBACK") == 0) token.type = TOKEN_ROLLBACK;
        else if (strcasecmp(token.value, "PRIMARY") == 0) token.type = TOKEN_PRIMARY;
        else if (strcasecmp(token.value, "KEY") == 0) token.type = TOKEN_KEY;
        else token.type = TOKEN_IDENTIFIER;  // 普通标识符
        
        *sql = s;
        return token;
    }
    
    // 2. 字符串（单引号包裹）
    if (*s == '\'') {
        const char* start = s + 1;
        s++; (*pos)++;  // 跳过开头单引号
        const char* str_start = s;  // 记录字符串内容起始位置
        
        while (*s && *s != '\'') {  // 寻找闭合单引号
            if (*s == '\n') {  // 字符串跨行吗？
                (*line)++;
                *pos = 0;
            } else {
                (*pos)++;
            }
            s++;
        }
        
        // 修复：处理未闭合的字符串（避免后续令牌解析混乱）
        int len = s - str_start;
        if (len > 0) {
            strncpy(token.value, str_start, len);
            token.value[len] = '\0';
        } else {
            token.value[0] = '\0';  // 空字符串
        }
        token.type = TOKEN_STRING;
        
        if (*s == '\'') {  // 跳过闭合单引号
            s++; (*pos)++;
        } else {
            // 未闭合的字符串（上层解析器会报错）
            token.type = TOKEN_STRING;  // 仍标记为字符串，但内容不完整
        }
        
        *sql = s;
        return token;
    }
    
    // 3. 数字（整数或负数）
    if (isdigit((unsigned char)*s) || (*s == '-' && isdigit((unsigned char)*(s + 1)))) {
        const char* start = s;
        if (*s == '-') {  // 处理负数（确保负号后有数字）
            s++; (*pos)++;
        }
        
        // 收集所有数字
        while (isdigit((unsigned char)*s)) {
            s++; (*pos)++;
        }
        
        int len = s - start;
        strncpy(token.value, start, len);
        token.value[len] = '\0';
        token.type = TOKEN_NUMBER;
        
        *sql = s;
        return token;
    }
    
    // 4. 运算符和符号（修复优先级和完整性）
    switch (*s) {
        case '=':  // 单独的等号（修复UPDATE中=的识别）
            token.type = TOKEN_EQ;
            s++; (*pos)++;
            break;
        case '<':  // 小于、小于等于、不等于
            s++; (*pos)++;
            if (*s == '=') {
                token.type = TOKEN_LE;  // <=
                s++; (*pos)++;
            } else if (*s == '>') {
                token.type = TOKEN_NE;  // <>（不等于）
                s++; (*pos)++;
            } else {
                token.type = TOKEN_LT;  // <
            }
            break;
        case '>':  // 大于、大于等于
            s++; (*pos)++;
            if (*s == '=') {
                token.type = TOKEN_GE;  // >=
                s++; (*pos)++;
            } else {
                token.type = TOKEN_GT;  // >
            }
            break;
        case '(': 
            token.type = TOKEN_LPAREN;
            s++; (*pos)++;
            break;
        case ')': 
            token.type = TOKEN_RPAREN;
            s++; (*pos)++;
            break;
        case ',': 
            token.type = TOKEN_COMMA;
            s++; (*pos)++;
            break;
        case ';': 
            token.type = TOKEN_SEMICOLON;  // 语句结束符
            s++; (*pos)++;
            break;
        case '.': 
            token.type = TOKEN_DOT;
            s++; (*pos)++;
            break;
        case '*': 
            token.type = TOKEN_ASTERISK;  // 通配符或乘法
            s++; (*pos)++;
            break;
        default:  // 未知符号（修复错误类型）
            token.type = TOKEN_EOF;  // 可用TOKEN_UNKNOWN（若定义）
            s++; (*pos)++;
            break;
    }
    
    *sql = s;
    return token;
}
#endif


// 解析表达式
static int parse_expression(MiniSQL* db, const char** sql, Expr** expr, int* line, int* pos) {
    *expr = (Expr*)malloc(sizeof(Expr));
    if (!*expr) {
        set_error(db, "Out of memory");
        return MINISQL_NOMEM;
    }
    memset(*expr, 0, sizeof(Expr));
    (*expr)->left = NULL;
    (*expr)->right = NULL;
    
    Token token = sql_next_token(sql, line, pos);
    
    // 处理标识符（列名）
    if (token.type == TOKEN_IDENTIFIER) {
        strncpy((*expr)->column, token.value, MAX_COLUMN_NAME - 1);
        
        // 解析比较运算符
        Token op_token = sql_next_token(sql, line, pos);
        if (op_token.type != TOKEN_EQ && op_token.type != TOKEN_NE &&
            op_token.type != TOKEN_LT && op_token.type != TOKEN_GT &&
            op_token.type != TOKEN_LE && op_token.type != TOKEN_GE) {
            set_error(db, "Expected comparison operator at line %d, position %d", op_token.line, op_token.pos);
            free_expr(*expr);
            *expr = NULL;
            return MINISQL_ERROR;
        }
        (*expr)->op = op_token.type;
        
        // 解析值
        if (parse_value(db, sql, &(*expr)->value, line, pos) != MINISQL_OK) {
            free_expr(*expr);
            *expr = NULL;
            return MINISQL_ERROR;
        }
        
        // 检查是否有AND/OR连接的表达式
        Token next_tok = sql_next_token(sql, line, pos);
        if (next_tok.type == TOKEN_AND || next_tok.type == TOKEN_OR) {
            // 创建新的表达式节点
            Expr* new_expr = (Expr*)malloc(sizeof(Expr));
            if (!new_expr) {
                set_error(db, "Out of memory");
                free_expr(*expr);
                *expr = NULL;
                return MINISQL_NOMEM;
            }
            memset(new_expr, 0, sizeof(Expr));
            new_expr->left = *expr;
            new_expr->is_and = (next_tok.type == TOKEN_AND);
            
            // 递归解析右侧表达式
            if (parse_expression(db, sql, &new_expr->right, line, pos) != MINISQL_OK) {
                free_expr(new_expr);
                *expr = NULL;
                return MINISQL_ERROR;
            }
            
            *expr = new_expr;
        } else {
            // 回溯，将令牌放回
            *sql = *sql - (next_tok.pos - token.pos);
            *pos = token.pos;
        }
        
        return MINISQL_OK;
    }
    
    // 处理括号表达式
    if (token.type == TOKEN_LPAREN) {
        if (parse_expression(db, sql, expr, line, pos) != MINISQL_OK) {
            free_expr(*expr);
            *expr = NULL;
            return MINISQL_ERROR;
        }
        
        Token closing = sql_next_token(sql, line, pos);
        if (closing.type != TOKEN_RPAREN) {
            set_error(db, "Expected closing parenthesis at line %d, position %d", closing.line, closing.pos);
            free_expr(*expr);
            *expr = NULL;
            return MINISQL_ERROR;
        }
        
        // 检查是否有AND/OR连接的表达式
        Token next_tok = sql_next_token(sql, line, pos);
        if (next_tok.type == TOKEN_AND || next_tok.type == TOKEN_OR) {
            // 创建新的表达式节点
            Expr* new_expr = (Expr*)malloc(sizeof(Expr));
            if (!new_expr) {
                set_error(db, "Out of memory");
                free_expr(*expr);
                *expr = NULL;
                return MINISQL_NOMEM;
            }
            memset(new_expr, 0, sizeof(Expr));
            new_expr->left = *expr;
            new_expr->is_and = (next_tok.type == TOKEN_AND);
            
            // 递归解析右侧表达式
            if (parse_expression(db, sql, &new_expr->right, line, pos) != MINISQL_OK) {
                free_expr(new_expr);
                *expr = NULL;
                return MINISQL_ERROR;
            }
            
            *expr = new_expr;
        } else {
            // 回溯，将令牌放回
            *sql = *sql - (next_tok.pos - token.pos);
            *pos = token.pos;
        }
        
        return MINISQL_OK;
    }
    
    set_error(db, "Unexpected token at line %d, position %d: %s", token.line, token.pos, token.value);
    free_expr(*expr);
    *expr = NULL;
    return MINISQL_ERROR;
}

// 解析WHERE子句
static int parse_where_clause(MiniSQL* db, const char** sql, Expr** expr, int* line, int* pos) {
    // 调用者（如parse_update/parse_select）已确认WHERE令牌存在，直接解析条件表达式
    return parse_expression(db, sql, expr, line, pos);
}

static int parse_select(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos) {
    stmt->type = OP_SELECT;
    stmt->select_all = 0;
    stmt->column_count = 0;
    stmt->where_clause = NULL;

    // 1. 解析列（*或多列）
    Token token = sql_next_token(sql, line, pos);
    if (token.type == TOKEN_ASTERISK) {
        // 处理 SELECT * 的核心修复
        stmt->select_all = 1;

        // 关键修复：必须显式检查并解析 FROM 关键字
        Token from_tok = sql_next_token(sql, line, pos);
        if (from_tok.type != TOKEN_FROM) {
            set_error(db, "Expected FROM after * (line %d)", from_tok.line);
            return MINISQL_ERROR;
        }
    } else if (token.type == TOKEN_IDENTIFIER) {
        // 处理指定列（原有逻辑不变）
        strncpy(stmt->columns[stmt->column_count++], token.value, MAX_COLUMN_NAME - 1);

        // 循环处理后续列（通过逗号分隔）
        while (1) {
            Token comma_tok = sql_next_token(sql, line, pos);
            if (comma_tok.type != TOKEN_COMMA) {
                // 非逗号 → 检查是否为 FROM
                if (comma_tok.type != TOKEN_FROM) {
                    set_error(db, "Expected FROM after columns (line %d)", comma_tok.line);
                    return MINISQL_ERROR;
                }
                break;
            }

            // 解析下一列
            Token col_tok = sql_next_token(sql, line, pos);
            if (col_tok.type != TOKEN_IDENTIFIER) {
                set_error(db, "Expected column name after comma (line %d)", col_tok.line);
                return MINISQL_ERROR;
            }
            if (stmt->column_count >= MAX_COLUMNS) {
                set_error(db, "Too many columns (max %d)", MAX_COLUMNS);
                return MINISQL_ERROR;
            }
            strncpy(stmt->columns[stmt->column_count++], col_tok.value, MAX_COLUMN_NAME - 1);
        }
    } else {
        set_error(db, "Expected * or column name (line %d)", token.line);
        return MINISQL_ERROR;
    }

    // 2. 解析表名（此时已确认FROM关键字存在）
    Token table_tok = sql_next_token(sql, line, pos);
    if (table_tok.type != TOKEN_IDENTIFIER) {
        set_error(db, "Expected table name after FROM (line %d)", table_tok.line);
        return MINISQL_ERROR;
    }
    strncpy(stmt->table_name, table_tok.value, MAX_TABLE_NAME - 1);

    // 3. 解析可选的WHERE子句
    Token where_tok = sql_next_token(sql, line, pos);
    if (where_tok.type == TOKEN_WHERE) {
        if (parse_where_clause(db, sql, &stmt->where_clause, line, pos) != MINISQL_OK) {
            return MINISQL_ERROR;
        }
    } else {
        // 无WHERE子句 → 回溯
        *sql -= (where_tok.pos - table_tok.pos);
        *pos = table_tok.pos;
    }

    return MINISQL_OK;
}


// 解析INSERT语句
static int parse_insert(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos) {
    stmt->type = OP_INSERT;
    stmt->value_count = 0;
    
    // 解析INTO
    Token into_token = sql_next_token(sql, line, pos);
    if (into_token.type != TOKEN_INTO) {
        set_error(db, "Expected INTO at line %d, position %d", into_token.line, into_token.pos);
        return MINISQL_ERROR;
    }
    
    // 解析表名
    Token table_token = sql_next_token(sql, line, pos);
    if (table_token.type != TOKEN_IDENTIFIER) {
        set_error(db, "Expected table name at line %d, position %d", table_token.line, table_token.pos);
        return MINISQL_ERROR;
    }
    strncpy(stmt->table_name, table_token.value, MAX_TABLE_NAME - 1);
    
    // 解析VALUES
    Token values_token = sql_next_token(sql, line, pos);
    if (values_token.type != TOKEN_VALUES) {
        set_error(db, "Expected VALUES at line %d, position %d", values_token.line, values_token.pos);
        return MINISQL_ERROR;
    }
    
    // 解析值列表
    Token lparen_token = sql_next_token(sql, line, pos);
    if (lparen_token.type != TOKEN_LPAREN) {
        set_error(db, "Expected ( after VALUES at line %d, position %d", lparen_token.line, lparen_token.pos);
        return MINISQL_ERROR;
    }
    
    while (1) {
        // 解析值
        if (stmt->value_count >= MAX_COLUMNS) {
            set_error(db, "Too many values in INSERT statement");
            return MINISQL_ERROR;
        }
        
        if (parse_value(db, sql, &stmt->values[stmt->value_count], line, pos) != MINISQL_OK) {
            return MINISQL_ERROR;
        }
        stmt->value_count++;
        
        // 检查下一个令牌
        Token next_tok = sql_next_token(sql, line, pos);
        if (next_tok.type == TOKEN_RPAREN) {
            break;
        } else if (next_tok.type == TOKEN_COMMA) {
            continue;
        } else {
            set_error(db, "Expected , or ) in value list at line %d, position %d", next_tok.line, next_tok.pos);
            return MINISQL_ERROR;
        }
    }
    
    return MINISQL_OK;
}


// 3. 修复DELETE语句的解析问题
static int parse_delete(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos) {
    stmt->type = OP_DELETE;
    stmt->where_clause = NULL;
    
    // 关键修复：确保正确解析FROM子句
    Token from_token = sql_next_token(sql, line, pos);
    if (from_token.type != TOKEN_FROM) {
        set_error(db, "Expected FROM after DELETE at line %d, position %d", from_token.line, from_token.pos);
        return MINISQL_ERROR;
    }
    
    // 解析表名
    Token table_token = sql_next_token(sql, line, pos);
    if (table_token.type != TOKEN_IDENTIFIER) {
        set_error(db, "Expected table name after FROM at line %d, position %d", table_token.line, table_token.pos);
        return MINISQL_ERROR;
    }
    strncpy(stmt->table_name, table_token.value, MAX_TABLE_NAME - 1);
    
    // 解析WHERE子句（如果有）
    Token where_token = sql_next_token(sql, line, pos);
    if (where_token.type == TOKEN_WHERE) {
        // 回溯并解析WHERE条件
        *sql -= (where_token.pos - table_token.pos);
        *pos = table_token.pos;
        if (parse_where_clause(db, sql, &stmt->where_clause, line, pos) != MINISQL_OK) {
            return MINISQL_ERROR;
        }
    } else {
        // 回溯
        *sql -= (where_token.pos - table_token.pos);
        *pos = table_token.pos;
    }
    
    return MINISQL_OK;
}

// 修复parse_update函数中WHERE子句的解析逻辑
static int parse_update(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos) {
    stmt->type = OP_UPDATE;
    stmt->update_count = 0;
    stmt->where_clause = NULL;

    // 解析表名
    Token table_tok = sql_next_token(sql, line, pos);
    if (table_tok.type != TOKEN_IDENTIFIER) {
        set_error(db, "Expected table name after UPDATE (line %d)", table_tok.line);
        return MINISQL_ERROR;
    }
    strncpy(stmt->table_name, table_tok.value, MAX_TABLE_NAME - 1);

    // 解析SET子句
    Token set_tok = sql_next_token(sql, line, pos);
    if (set_tok.type != TOKEN_SET) {
        set_error(db, "Expected SET after table name (line %d)", set_tok.line);
        return MINISQL_ERROR;
    }

    // 解析SET后的列=值（支持多个）
    while (1) {
        // 解析列名
        Token col_tok = sql_next_token(sql, line, pos);
        if (col_tok.type != TOKEN_IDENTIFIER) {
            set_error(db, "Expected column name in SET (line %d)", col_tok.line);
            return MINISQL_ERROR;
        }
        strncpy(stmt->update_columns[stmt->update_count], col_tok.value, MAX_COLUMN_NAME - 1);

        // 解析等号
        Token eq_tok = sql_next_token(sql, line, pos);
        if (eq_tok.type != TOKEN_EQ) {
            set_error(db, "Expected '=' after column (line %d)", eq_tok.line);
            return MINISQL_ERROR;
        }

        // 解析值
        if (parse_value(db, sql, &stmt->update_values[stmt->update_count], line, pos) != MINISQL_OK) {
            return MINISQL_ERROR;
        }
        stmt->update_count++;

        // 检查下一个令牌（修复WHERE子句解析）
        Token next_tok = sql_next_token(sql, line, pos);
        if (next_tok.type == TOKEN_WHERE) {
            // 正确解析WHERE子句：无需回溯，直接处理已识别的WHERE令牌
            if (parse_where_clause(db, sql, &stmt->where_clause, line, pos) != MINISQL_OK) {
                return MINISQL_ERROR;
            }
            break;
        } else if (next_tok.type == TOKEN_SEMICOLON || next_tok.type == TOKEN_EOF) {
            // 无WHERE子句，正常结束
            break;
        } else if (next_tok.type != TOKEN_COMMA) {
            set_error(db, "Expected ',' or 'WHERE' after value (line %d)", next_tok.line);
            return MINISQL_ERROR;
        }
    }

    return MINISQL_OK;
}
    

// 解析CREATE TABLE语句
static int parse_create_table(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos) {
    stmt->type = OP_CREATE_TABLE;
    stmt->create_column_count = 0;
    
    // 解析表名
    Token table_token = sql_next_token(sql, line, pos);
    if (table_token.type != TOKEN_IDENTIFIER) {
        set_error(db, "Expected table name at line %d, position %d", table_token.line, table_token.pos);
        return MINISQL_ERROR;
    }
    strncpy(stmt->table_name, table_token.value, MAX_TABLE_NAME - 1);
    
    // 解析左括号
    Token lparen_token = sql_next_token(sql, line, pos);
    if (lparen_token.type != TOKEN_LPAREN) {
        set_error(db, "Expected ( after table name at line %d, position %d", lparen_token.line, lparen_token.pos);
        return MINISQL_ERROR;
    }
    
    // 解析列定义
    while (1) {
        if (stmt->create_column_count >= MAX_COLUMNS) {
            set_error(db, "Too many columns in table definition");
            return MINISQL_ERROR;
        }
        
        // 列名
        Token col_token = sql_next_token(sql, line, pos);
        if (col_token.type != TOKEN_IDENTIFIER) {
            set_error(db, "Expected column name at line %d, position %d", col_token.line, col_token.pos);
            return MINISQL_ERROR;
        }
        strncpy(stmt->create_columns[stmt->create_column_count].name, col_token.value, MAX_COLUMN_NAME - 1);
        
        // 列类型
        Token type_token = sql_next_token(sql, line, pos);
        if (type_token.type != TOKEN_INT && type_token.type != TOKEN_TEXT) {
            set_error(db, "Expected INT or TEXT at line %d, position %d", type_token.line, type_token.pos);
            return MINISQL_ERROR;
        }
        stmt->create_columns[stmt->create_column_count].type = 
            (type_token.type == TOKEN_INT) ? MINISQL_TYPE_INT : MINISQL_TYPE_TEXT;
        stmt->create_columns[stmt->create_column_count].is_primary = 0;
        
        // 检查是否为主键
        Token next_tok = sql_next_token(sql, line, pos);
        if (next_tok.type == TOKEN_PRIMARY) {
            Token key_token = sql_next_token(sql, line, pos);
            if (key_token.type != TOKEN_KEY) {
                set_error(db, "Expected KEY after PRIMARY at line %d, position %d", key_token.line, key_token.pos);
                return MINISQL_ERROR;
            }
            stmt->create_columns[stmt->create_column_count].is_primary = 1;
            next_tok = sql_next_token(sql, line, pos);
        }
        
        stmt->create_column_count++;
        
        // 检查下一个令牌
        if (next_tok.type == TOKEN_RPAREN) {
            break;
        } else if (next_tok.type == TOKEN_COMMA) {
            continue;
        } else {
            set_error(db, "Expected , or ) in column list at line %d, position %d", next_tok.line, next_tok.pos);
            return MINISQL_ERROR;
        }
    }
    
    return MINISQL_OK;
}

// 解析CREATE INDEX语句
static int parse_create_index(MiniSQL* db, const char** sql, Statement* stmt, int* line, int* pos) {
    stmt->type = OP_CREATE_INDEX;
    
    // 解析索引名
    Token index_token = sql_next_token(sql, line, pos);
    if (index_token.type != TOKEN_IDENTIFIER) {
        set_error(db, "Expected index name at line %d, position %d", index_token.line, index_token.pos);
        return MINISQL_ERROR;
    }
    // 索引名目前未使用，因为我们使用表名+列名唯一标识索引
    
    // 解析ON
    Token on_token = sql_next_token(sql, line, pos);
    if (on_token.type != TOKEN_ON) {
        set_error(db, "Expected ON at line %d, position %d", on_token.line, on_token.pos);
        return MINISQL_ERROR;
    }
    
    // 解析表名
    Token table_token = sql_next_token(sql, line, pos);
    if (table_token.type != TOKEN_IDENTIFIER) {
        set_error(db, "Expected table name at line %d, position %d", table_token.line, table_token.pos);
        return MINISQL_ERROR;
    }
    strncpy(stmt->table_name, table_token.value, MAX_TABLE_NAME - 1);
    
    // 解析左括号
    Token lparen_token = sql_next_token(sql, line, pos);
    if (lparen_token.type != TOKEN_LPAREN) {
        set_error(db, "Expected ( after table name at line %d, position %d", lparen_token.line, lparen_token.pos);
        return MINISQL_ERROR;
    }
    
    // 解析列名
    Token col_token = sql_next_token(sql, line, pos);
    if (col_token.type != TOKEN_IDENTIFIER) {
        set_error(db, "Expected column name at line %d, position %d", col_token.line, col_token.pos);
        return MINISQL_ERROR;
    }
    strncpy(stmt->index_column, col_token.value, MAX_COLUMN_NAME - 1);
    
    // 解析右括号
    Token rparen_token = sql_next_token(sql, line, pos);
    if (rparen_token.type != TOKEN_RPAREN) {
        set_error(db, "Expected ) after column name at line %d, position %d", rparen_token.line, rparen_token.pos);
        return MINISQL_ERROR;
    }
    
    return MINISQL_OK;
}

// 解析SQL语句
static int parse_statement(MiniSQL* db, const char* sql, Statement* stmt) {
    const char* s = sql;
    int line = 1;
    int pos = 0;
    memset(stmt, 0, sizeof(Statement));
    
    Token token = sql_next_token(&s, &line, &pos);
    switch (token.type) {
        case TOKEN_SELECT:
            return parse_select(db, &s, stmt, &line, &pos);
        case TOKEN_INSERT:
            return parse_insert(db, &s, stmt, &line, &pos);
        case TOKEN_UPDATE:
            return parse_update(db, &s, stmt, &line, &pos);
        case TOKEN_DELETE:
            return parse_delete(db, &s, stmt, &line, &pos);
        case TOKEN_CREATE: {
            Token next_tok = sql_next_token(&s, &line, &pos);
            if (next_tok.type == TOKEN_TABLE) {
                return parse_create_table(db, &s, stmt, &line, &pos);
            } else if (next_tok.type == TOKEN_INDEX) {
                return parse_create_index(db, &s, stmt, &line, &pos);
            } else {
                set_error(db, "Expected TABLE or INDEX after CREATE at line %d, position %d", next_tok.line, next_tok.pos);
                return MINISQL_ERROR;
            }
            break;
        }
        case TOKEN_BEGIN:
            stmt->type = OP_BEGIN;
            return MINISQL_OK;
        case TOKEN_COMMIT:
            stmt->type = OP_COMMIT;
            return MINISQL_OK;
        case TOKEN_ROLLBACK:
            stmt->type = OP_ROLLBACK;
            return MINISQL_OK;
        default:
            set_error(db, "Unexpected token at line %d, position %d: %s", token.line, token.pos, token.value);
            return MINISQL_ERROR;
    }
    
    return MINISQL_OK;
}

// 执行SQL语句
int minisql_exec(MiniSQL* db, const char* sql, ResultSet** result) {
    if (!db || !db->is_open || !sql) {
        return MINISQL_INVALID;
    }
    
    // 清除之前的错误
    if (db->err_msg) {
        free(db->err_msg);
        db->err_msg = NULL;
    }
    
    *result = NULL;
    Statement stmt;
    
    // 解析语句
    int rc = parse_statement(db, sql, &stmt);
    if (rc != MINISQL_OK) {
        return rc;
    }
    
    // 执行语句
    switch (stmt.type) {
        case OP_CREATE_TABLE:
            rc = create_table(db, stmt.table_name, stmt.create_columns, stmt.create_column_count);
            break;
        case OP_INSERT:
            rc = insert_row(db, stmt.table_name, stmt.values, stmt.value_count);
            // 释放字符串值
            for (int i = 0; i < stmt.value_count; i++) {
                if (stmt.values[i].type == MINISQL_TYPE_TEXT) {
                    free(stmt.values[i].as.s);
                }
            }
            break;
        case OP_SELECT: {
            const char* columns[MAX_COLUMNS];
            for (int i = 0; i < stmt.column_count; i++) {
                columns[i] = stmt.columns[i];
            }
            *result = select_rows(db, stmt.table_name, columns, stmt.column_count, stmt.select_all, stmt.where_clause);
            rc = *result ? MINISQL_OK : MINISQL_ERROR;
            break;
        }
        case OP_DELETE:
            rc = delete_rows(db, stmt.table_name, stmt.where_clause);
            break;
        case OP_UPDATE: {
            char* columns[MAX_COLUMNS];
            for (int i = 0; i < stmt.update_count; i++) {
                columns[i] = stmt.update_columns[i];
            }
            rc = update_rows(db, stmt.table_name, columns, stmt.update_values, stmt.update_count, stmt.where_clause);
            // 释放字符串值
            for (int i = 0; i < stmt.update_count; i++) {
                if (stmt.update_values[i].type == MINISQL_TYPE_TEXT) {
                    free(stmt.update_values[i].as.s);
                }
            }
            break;
        }
        case OP_CREATE_INDEX:
            rc = create_index(db, "", stmt.table_name, stmt.index_column);
            break;
        case OP_BEGIN:
            rc = begin_transaction(db);
            break;
        case OP_COMMIT:
            rc = commit_transaction(db);
            break;
        case OP_ROLLBACK:
            rc = rollback_transaction(db);
            break;
        default:
            set_error(db, "Unsupported statement type");
            rc = MINISQL_ERROR;
            break;
    }
    
    return rc;
}

// 释放结果集
void minisql_free_result(ResultSet* result) {
    if (!result) return;
    
    free(result->rows);
    free(result);
}

// 获取错误消息
const char* minisql_errmsg(MiniSQL* db) {
    return db->err_msg ? db->err_msg : "No error";
}

// 保存数据库到磁盘
static int save_to_disk(MiniSQL* db) {
    if (!db || !db->is_open) return MINISQL_INVALID;
    
    // 构建数据文件路径
    char data_path[PATH_MAX];
    snprintf(data_path, PATH_MAX, "%s.dat", db->db_path);
    
    // 打开文件
    FILE* f = fopen(data_path, "wb");
    if (!f) {
        set_error(db, "Failed to open database file for writing: %s", strerror(errno));
        return MINISQL_IOERR;
    }
    
    // 写入表数量
    int table_count = 0;
    Table* table = db->tables;
    while (table) {
        table_count++;
        table = table->next;
    }
    fwrite(&table_count, sizeof(int), 1, f);
    
    // 写入每个表
    table = db->tables;
    while (table) {
        // 写入表名
        int name_len = strlen(table->name);
        fwrite(&name_len, sizeof(int), 1, f);
        fwrite(table->name, 1, name_len, f);
        
        // 写入列数量
        fwrite(&table->column_count, sizeof(int), 1, f);
        
        // 写入列定义
        for (int i = 0; i < table->column_count; i++) {
            // 列名
            int col_name_len = strlen(table->columns[i].name);
            fwrite(&col_name_len, sizeof(int), 1, f);
            fwrite(table->columns[i].name, 1, col_name_len, f);
            
            // 列类型和主键标志
            fwrite(&table->columns[i].type, sizeof(int), 1, f);
            fwrite(&table->columns[i].is_primary, sizeof(int), 1, f);
        }
        
        // 写入行数量
        fwrite(&table->row_count, sizeof(int), 1, f);
        
        // 写入下一个行ID
        fwrite(&table->next_row_id, sizeof(int64_t), 1, f);
        
        // 写入行数据
        Row* row = table->rows;
        while (row) {
            // 行ID
            fwrite(&row->row_id, sizeof(int64_t), 1, f);
            
            // 写入每个值
            for (int i = 0; i < table->column_count; i++) {
                // 值类型
                fwrite(&row->values[i].type, sizeof(int), 1, f);
                
                // 值数据
                switch (row->values[i].type) {
                    case MINISQL_TYPE_INT:
                        fwrite(&row->values[i].as.i, sizeof(int64_t), 1, f);
                        break;
                    case MINISQL_TYPE_TEXT: {
                        int len = strlen(row->values[i].as.s);
                        fwrite(&len, sizeof(int), 1, f);
                        fwrite(row->values[i].as.s, 1, len, f);
                        break;
                    }
                    default:
                        break;
                }
            }
            
            row = row->next;
        }
        
        table = table->next;
    }
    
    fclose(f);
    return MINISQL_OK;
}

// 从磁盘加载数据库
static int load_from_disk(MiniSQL* db) {
    if (!db) return MINISQL_INVALID;
    
    // 构建数据文件路径
    char data_path[PATH_MAX];
    snprintf(data_path, PATH_MAX, "%s.dat", db->db_path);
    
    // 检查文件是否存在
#ifdef _WIN32
    FILE* f = fopen(data_path, "rb");
#else
    struct stat st;
    if (stat(data_path, &st) != 0) {
        // 文件不存在，初始化空数据库
        db->is_open = 1;
        return MINISQL_OK;
    }
    FILE* f = fopen(data_path, "rb");
#endif
    
    if (!f) {
        set_error(db, "Failed to open database file for reading: %s", strerror(errno));
        return MINISQL_IOERR;
    }
    
    // 读取表数量
    int table_count;
    if (fread(&table_count, sizeof(int), 1, f) != 1) {
        fclose(f);
        set_error(db, "Failed to read table count");
        return MINISQL_IOERR;
    }
    
    // 读取每个表
    for (int t = 0; t < table_count; t++) {
        Table* table = (Table*)malloc(sizeof(Table));
        if (!table) {
            fclose(f);
            set_error(db, "Out of memory");
            return MINISQL_NOMEM;
        }
        memset(table, 0, sizeof(Table));
        table->next = db->tables;
        db->tables = table;
        
        // 读取表名
        int name_len;
        if (fread(&name_len, sizeof(int), 1, f) != 1) {
            fclose(f);
            set_error(db, "Failed to read table name length");
            return MINISQL_IOERR;
        }
        if (name_len >= MAX_TABLE_NAME) name_len = MAX_TABLE_NAME - 1;
        if (fread(table->name, 1, name_len, f) != (size_t)name_len) {
            fclose(f);
            set_error(db, "Failed to read table name");
            return MINISQL_IOERR;
        }
        table->name[name_len] = '\0';
        
        // 读取列数量
        if (fread(&table->column_count, sizeof(int), 1, f) != 1) {
            fclose(f);
            set_error(db, "Failed to read column count");
            return MINISQL_IOERR;
        }
        if (table->column_count > MAX_COLUMNS) table->column_count = MAX_COLUMNS;
        
        // 读取列定义
        for (int i = 0; i < table->column_count; i++) {
            // 列名
            int col_name_len;
            if (fread(&col_name_len, sizeof(int), 1, f) != 1) {
                fclose(f);
                set_error(db, "Failed to read column name length");
                return MINISQL_IOERR;
            }
            if (col_name_len >= MAX_COLUMN_NAME) col_name_len = MAX_COLUMN_NAME - 1;
            if (fread(table->columns[i].name, 1, col_name_len, f) != (size_t)col_name_len) {
                fclose(f);
                set_error(db, "Failed to read column name");
                return MINISQL_IOERR;
            }
            table->columns[i].name[col_name_len] = '\0';
            
            // 列类型和主键标志
            if (fread(&table->columns[i].type, sizeof(int), 1, f) != 1) {
                fclose(f);
                set_error(db, "Failed to read column type");
                return MINISQL_IOERR;
            }
            if (fread(&table->columns[i].is_primary, sizeof(int), 1, f) != 1) {
                fclose(f);
                set_error(db, "Failed to read primary key flag");
                return MINISQL_IOERR;
            }
        }
        
        // 读取行数量
        if (fread(&table->row_count, sizeof(int), 1, f) != 1) {
            fclose(f);
            set_error(db, "Failed to read row count");
            return MINISQL_IOERR;
        }
        
        // 读取下一个行ID
        if (fread(&table->next_row_id, sizeof(int64_t), 1, f) != 1) {
            fclose(f);
            set_error(db, "Failed to read next row ID");
            return MINISQL_IOERR;
        }
        
        // 读取行数据
        Row* last_row = NULL;
        for (int r = 0; r < table->row_count; r++) {
            Row* row = (Row*)malloc(sizeof(Row));
            if (!row) {
                fclose(f);
                set_error(db, "Out of memory");
                return MINISQL_NOMEM;
            }
            memset(row, 0, sizeof(Row));
            row->values = (Value*)malloc(table->column_count * sizeof(Value));
            if (!row->values) {
                free(row);
                fclose(f);
                set_error(db, "Out of memory");
                return MINISQL_NOMEM;
            }
            memset(row->values, 0, table->column_count * sizeof(Value));
            
            // 行ID
            if (fread(&row->row_id, sizeof(int64_t), 1, f) != 1) {
                fclose(f);
                set_error(db, "Failed to read row ID");
                return MINISQL_IOERR;
            }
            
            // 读取每个值
            for (int i = 0; i < table->column_count; i++) {
                // 值类型
                if (fread(&row->values[i].type, sizeof(int), 1, f) != 1) {
                    fclose(f);
                    set_error(db, "Failed to read value type");
                    return MINISQL_IOERR;
                }
                
                // 值数据
                switch (row->values[i].type) {
                    case MINISQL_TYPE_INT:
                        if (fread(&row->values[i].as.i, sizeof(int64_t), 1, f) != 1) {
                            fclose(f);
                            set_error(db, "Failed to read integer value");
                            return MINISQL_IOERR;
                        }
                        break;
                    case MINISQL_TYPE_TEXT: {
                        int len;
                        if (fread(&len, sizeof(int), 1, f) != 1) {
                            fclose(f);
                            set_error(db, "Failed to read string length");
                            return MINISQL_IOERR;
                        }
                        row->values[i].as.s = (char*)malloc(len + 1);
                        if (!row->values[i].as.s) {
                            fclose(f);
                            set_error(db, "Out of memory");
                            return MINISQL_NOMEM;
                        }
                        if (fread(row->values[i].as.s, 1, len, f) != (size_t)len) {
                            fclose(f);
                            set_error(db, "Failed to read string value");
                            return MINISQL_IOERR;
                        }
                        row->values[i].as.s[len] = '\0';
                        break;
                    }
                    default:
                        break;
                }
            }
            
            // 添加到链表
            row->prev = last_row;
            row->next = NULL;
            if (last_row) {
                last_row->next = row;
            } else {
                table->rows = row;
            }
            last_row = row;
        }
    }
    
    fclose(f);
    db->is_open = 1;
    return MINISQL_OK;
}


// 4. 修复print_result_set，支持color print和MD格式输出
static void print_result_set(ResultSet* result) {
    if (!result || result->row_count == 0) {
        #ifdef HAS_COLOR_PRINT
        cprintf("No results\n" );
        #else
        printf("No results\n");
        #endif
        return;
    }
    
    // MD格式表头
    #ifdef HAS_COLOR_PRINT
    cprintf( "| ");
    #else
    printf("| ");
    #endif
    for (int i = 0; i < result->column_count; i++) {
        #ifdef HAS_COLOR_PRINT
        cprintf("%-15s | ", result->columns[i]);
        #else
        printf("%-15s | ", result->columns[i]);
        #endif
    }
    #ifdef HAS_COLOR_PRINT
    cprintf("\n" );
    #else
    printf("\n");
    #endif
    
    // MD分隔线
    #ifdef HAS_COLOR_PRINT
    cprintf( "| ");
    #else
    printf("| ");
    #endif
    for (int i = 0; i < result->column_count; i++) {
        #ifdef HAS_COLOR_PRINT
        cprintf("--------------- | ");
        #else
        printf("--------------- | ");
        #endif
    }
    #ifdef HAS_COLOR_PRINT
    cprintf("\n" );
    #else
    printf("\n");
    #endif
    
    // 行数据
    for (int r = 0; r < result->row_count; r++) {
        Row* row = result->rows[r];
        #ifdef HAS_COLOR_PRINT
        cprintf("| ");
        #else
        printf("| ");
        #endif
        for (int c = 0; c < result->column_count; c++) {
            int col_idx = column_index(result->table, result->columns[c]);
            if (col_idx == -1) {
                #ifdef HAS_COLOR_PRINT
                cprintf("%-15s | ", "NULL");
                #else
                printf("%-15s | ", "NULL");
                #endif
                continue;
            }
            
            Value* val = &row->values[col_idx];
            switch (val->type) {
                case MINISQL_TYPE_INT:
                    #ifdef HAS_COLOR_PRINT
                    cprintf( "%-15lld | " , (long long)val->as.i);
                    #else
                    printf("%-15lld | ", (long long)val->as.i);
                    #endif
                    break;
                case MINISQL_TYPE_TEXT:
                    #ifdef HAS_COLOR_PRINT
                    cprintf( "%-15s | " , val->as.s);
                    #else
                    printf("%-15s | ", val->as.s);
                    #endif
                    break;
                default:
                    #ifdef HAS_COLOR_PRINT
                    cprintf("%-15s | ", "NULL");
                    #else
                    printf("%-15s | ", "NULL");
                    #endif
                    break;
            }
        }
        printf("\n");
    }
    
    // 统计信息
    #ifdef HAS_COLOR_PRINT
    cprintf( "%d row(s) returned\n" , result->row_count);
    #else
    printf("%d row(s) returned\n", result->row_count);
    #endif
}

// REPL实现
void minisql_repl(MiniSQL* db) {
    if (!db || !db->is_open) return;
    #ifdef HAS_COLOR_PRINT
    cprintf("MiniSQL REPL (exit with .exit)\n");
    cprintf("Type your SQL commands:\n");
    #else
    printf("MiniSQL REPL (exit with .exit)\n");
    printf("Type your SQL commands:\n");
    #endif
    char* line;
    while (1) {
        printf("> ");
        line = NULL;
        size_t len = 0;
        ssize_t read = getline(&line, &len, stdin);
        
        if (read == -1) {
            break;
        }
        
        // 移除换行符
        if (read > 0 && line[read - 1] == '\n') {
            line[read - 1] = '\0';
        }
        
        // 检查退出命令
        if (strcmp(line, ".exit") == 0) {
            free(line);
            break;
        }
        
        // 执行SQL
        ResultSet* result = NULL;
        int rc = minisql_exec(db, line, &result);
        
        if (rc != MINISQL_OK) {
            printf("Error: %s\n", minisql_errmsg(db));
        } else if (result) {
            print_result_set(result);
            minisql_free_result(result);
        } else {
            #ifdef HAS_COLOR_PRINT
            cprintf("Command executed successfully\n");
            #else
            printf("Command executed successfully\n");
            #endif
        }
        
        free(line);
    }
}

#endif // MINISQL_IMPLEMENTATION

#ifdef __cplusplus
}
#endif

#endif // MINISQL_H